import React, { useEffect } from 'react'
import { useCounterReducer } from '@/hooks'
export default function Counter({
	id,
	currenCount,
	detail,
	cartList,
	cartListDispatch,
  max
}) {
	const [count, counterDispatch] = useCounterReducer(currenCount, max)
  useEffect(() => {
    console.log(cartList)
  }, [count])
  useEffect(() => {
    counterDispatch({ type: 'INPUT', payload: currenCount })
  }, [currenCount])
  useEffect(() => {
    if(count === 0) {
      cartListDispatch({ type: 'DELETE', payload: id })
    } else {
      const current = cartList.find(item => item.id === id)
      if(current) {
        cartListDispatch({ type: 'MODIFY', payload: {
          id,
          count
        } })
      } else {
        cartListDispatch({ type: 'ADD', payload: {
          count,
          ...detail
        } })
      }
    }
  }, [count])
	return (
		<div>
			<button onClick={() => counterDispatch({ type: 'MINUS'})}>-</button>
			<input
				type="number"
				value={count}
				onChange={e => counterDispatch({ type: 'INPUT', payload: e.target.value })}
			/>
			<button onClick={() => counterDispatch({ type: 'PLUS'})}>+</button>
		</div>
	)
}
